/*
 * Created on 2009-9-14
 * Copyright 2009 by www.xfok.net. All Rights Reserved
 *
 */

package com.swcw.platform.constants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.swcw.platform.external.constants.SysPropertiesUtil;

/**
 * @author YangHua 转载请注明出处：http://www.xfok.net/2009/10/124485.html
 * 文件上传 20180716cf
 */
@SuppressWarnings({"rawtypes"})
public class BusFtp {

	/**
	 * 连接sftp服务器Test
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public static ChannelSftp connect() {
		
		ChannelSftp sftp = null;
		String host = SysPropertiesUtil.getProperty("bus_host");
		String username = SysPropertiesUtil.getProperty("bus_userName");
		String password = SysPropertiesUtil.getProperty("bus_pwd");
		String po = SysPropertiesUtil.getProperty("bus_port");
		int port = Integer.parseInt(po);
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session sshSession = jsch.getSession(username, host, port);
			//System.out.println("开始连接服务器");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			//System.out.println("密码正确");
			//System.out.println("开始链接ftp");
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			//System.out.println("连接成功" + host + ".");
		} catch (Exception e) {
			System.out.println("连接资源服务器失败，数据没有备份！1");
		}
		return sftp;
	}

	/**
	 * 上传文件
	 * 
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 */
	public static void upload(String directory,String newFileName, InputStream localFilePath, ChannelSftp sftp) {
		System.out.println(directory);
		try{
			sftp.ls(directory); //首先查看下目录，如果不存在，系统会被错，捕获这个错，生成新的目录。
		}catch(Exception e1){
			try {
				sftp.mkdir(directory);
			} catch (SftpException e) {
				System.out.println("连接资源服务器失败，数据没有备份！2");
			}
		}
		try {
			sftp.cd(directory);
			sftp.put(localFilePath, newFileName);
		} catch (Exception e) {
			System.out.println("连接资源服务器失败，数据没有备份！3");
		}finally {
			if(localFilePath != null){
				try {
					localFilePath.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件
	 * @param saveFile
	 *            存在本地的路径
	 * @param sftp
	 */
	public void download(String directory, String downloadFile,
			String saveFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 */
	public static void delete(String deleteFile, ChannelSftp sftp) {
		try {
			sftp.rm(deleteFile);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
	}

	/**
	 * 列出目录下的文件
	 * 
	 * @param directory
	 *            要列出的目录
	 * @param sftp
	 * @return
	 * @throws SftpException
	 */
	public Vector listFiles(String directory, ChannelSftp sftp)
			throws SftpException {
		return sftp.ls(directory);
	}
	
	/**
	 * 下载文件
	 * @return 
	 */
	public static String download(String fileName,ChannelSftp sftp) {
		char sep = File.separatorChar;
		try {
			String directory = sep+"home"+sep+"busftp"+sep+"upload";
			sftp.cd(directory);
			File file = new File(fileName);
			sftp.get(fileName, new FileOutputStream(file));
			String path2 = SysPropertiesUtil.getProperty("path2");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");// 格式化时间
			String dates = sdf.format(new Date());
	        String url = "/busFile/" + dates + "/";
	        FileInputStream f = new FileInputStream(file);
			MySFTP.upload(path2+url, fileName, f, MySFTP.connect());
			sftp.rename(fileName, directory+sep+"mqsiarchive"+sep+fileName);
			file.delete();
			System.out.println("关闭连接1");
			try {
				sftp.getSession().disconnect();
			} catch (JSchException e) {
			}
			sftp.quit();
			sftp.disconnect();
			return url+fileName;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
		return null;
	}
	
	/**
	 * 上传文件
	 * @return 
	 */
	public static String upload(String fileName,ChannelSftp sftp) {
		char sep = File.separatorChar;
		String path2 = SysPropertiesUtil.getProperty("path2");
		fileName = path2 + fileName;
		String directory = fileName.substring(0, fileName.lastIndexOf(sep)+1);
		String name = fileName.substring(fileName.lastIndexOf(sep)+1, fileName.length());
		String type = name.substring(name.lastIndexOf("."), name.length());
		try {
			sftp.cd(directory);
			File file = new File(name);
			sftp.get(name, new FileOutputStream(file));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 格式化时间
			String dates = sdf.format(new Date());
	        FileInputStream f = new FileInputStream(file);
	        BusFtp.upload(sep+"home"+sep+"busftp"+sep+"download", dates + type, f, BusFtp.connect());
			file.delete();
			System.out.println("关闭连接1");
			try {
				sftp.getSession().disconnect();
			} catch (JSchException e) {
			}
			sftp.quit();
			sftp.disconnect();
			return dates + type;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(sftp!=null){
				System.out.println("关闭连接2");
				try {
					sftp.getSession().disconnect();
				} catch (JSchException e) {
				}
				sftp.quit();
				sftp.disconnect();
			}
		}
		return null;
	}
}